﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;

namespace quizzer_linq_3
{

    /**Class: Set_Creator
     * @author Samuel McCravy, Spencer Estes, and Jayson Park
     * @version 1.0
     * Course : ITEC 4860 Spring 2012
     * Written: March 1, 2012
     * 
     * This Class is suppose to create new sets and add questions to them.
     * 
     * Purpose: The purpose of this class is to allow admins to add sets and questions to those sets.(NOT DONE).
    */

    public partial class Set_Creator : Form
    {
        //This is used to access the database

        Quizzer_Data_Access dataAccess = new Quizzer_Data_Access();

        //A variable to flag if there are missing fields or invalid fields when adding a user's own questions

        Boolean unableToAddQuestion = false;

        //A variable to flag if there is a missing professor email when adding another professor's questions

        Boolean missingProfessor = false;

        //A variable to flag if there is a missing question when adding another professor's questions

        Boolean missingProfessorQuestion = false;

        //The user id of the current professor

        int userid;

        //When pulling from the QDB using getQuestion methods, this is the index for the 
        //question ID when splitting the returned string using the '|' delimiter.

        const int QUIZZERDB_QUESTION_QUESTIONID_INDEX = 0;

        //When pulling from the QDB using getQuestion methods, this is the index for the 
        //question title when splitting the returned string using the '|' delimiter.

        const int QUIZZERDB_QUESTION_TITLE_INDEX = 3;

        //When pulling from the QDB using getQuestion methods, this is the index for the 
        //Public? boolean when splitting the returned string using the '|' delimiter.

        const int QUIZZERDB_QUESTION_PUBLIC_INDEX = 5;

        //When pulling from the QDB using getQuestion methods, this is the index for the 
        //professor id number when splitting the returned string using the '|' delimiter.

        const int QUIZZERDB_QUESTION_PROFESSORID_INDEX = 13;

        //When pulling from the QDB using getGameSet methods, this is the index for the 
        //game set id when splitting the returned string using the '|' delimiter.

        const int QUIZZERDB_GAMESET_SETID_INDEX = 0;

        //When pulling from the QDB using getGameSet methods, this is the index for the 
        //game set name when splitting the returned string using the '|' delimiter.

        const int QUIZZERDB_GAMESET_SETNAME_INDEX = 1;

        //This is the index for the question id when splitting the questionComboBox using the ' ' delimiter.

        const int SETCREATOR_QUESTIONID_INDEX = 0;

        //When pulling from the QDB using getProfessor methods, this is the index for the 
        //professor's user id when splitting the returned string using the '|' delimiter.

        const int QUIZZERDB_PROFESSOR_USERID_INDEX = 0;

        //When pulling from the QDB using getProfessor methods, this is the index for the 
        //professor's email when splitting the returned string using the '|' delimiter.

        const int QUIZZERDB_PROFESSOR_EMAIL_INDEX = 3;

        //This is the default administrator user id

        const int ADMIN_LOGIN_USERID = 1000;

        public Set_Creator(int user_id)
        {
            InitializeComponent();
            //Added to grab all the questions -SE
            userid = user_id;
            GetAllPublicQuestions();
            GetAllPublicSets();
            populateQuestionRemoverComboBox();
            populateProfessorComboBox();
            defaultSelections();
        }

        /** Method: setCreatorBackButton_Click
         * @author: Samuel McCravy
         * Closes this form
         * 
         * @param sender sender of the action
         * @param e event is triggered
        */

        private void setCreatorBackButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /**Method: defaultSelections
         * @author: Jayson Park
         * This is simply to set the default index selections for the combo boxes in Set Creator
         */

        private void defaultSelections()
        {
            defaultQuestionComboBoxSelection();
            defaultQuestionRemoverComboBoxSelection();
            defaultSetCreatorSetIDBoxSelection();
            defaultProfessorQuestionComboBoxSelection();
            defaultProfessorEmailSelection();
        }

        /**Method: defaultQuestionRemoverComboBoxSelection
         * @author: Jayson Park
         * This is simply to set the default index selection questionRemoverComboBox in Set Creator
         */

        private void defaultQuestionRemoverComboBoxSelection()
        {
            if (questionRemoverComboBox.Items.Count != 0)
            {
                questionRemoverComboBox.SelectedIndex = 0;
            }
        }

        /**Method: defaultQuestionComboBoxSelection
         * @author: Jayson Park
         * This is simply to set the default index selection questionComboBox in Set Creator
         */

        private void defaultQuestionComboBoxSelection()
        {
            if (questionComboBox.Items.Count != 0)
            {
                questionComboBox.SelectedIndex = 0;
            }
            else
            {
                unableToAddQuestion = true;
            }
        }

        /**Method: defaultQuestionComboBoxSelection
         * @author: Jayson Park
         * This is simply to set the default index selection questionComboBox in Set Creator
         */

        private void defaultProfessorQuestionComboBoxSelection()
        {
            missingProfessorQuestion = false;
            if (questionProfessorComboBox.Items.Count != 0)
            {
                questionProfessorComboBox.SelectedIndex = 0;
            }
            else
            {
                missingProfessorQuestion = true;
            }
        }

        /**Method: defaultQuestionComboBoxSelection
         * @author: Jayson Park
         * This is simply to set the default index selection questionComboBox in Set Creator
         */

        private void defaultProfessorEmailSelection()
        {
            missingProfessor = false;
            if (lookupProfessorComboBox.Items.Count != 0)
            {
                lookupProfessorComboBox.SelectedIndex = 0;
            }
            else
            {
                missingProfessor = true;
            }
        }

        /**Method: defaultSetCreatorSetIDBoxSelection
         * @author: Jayson Park
         * This is simply to set the default index selection setCreatorSetIDBox in Set Creator
         */

        private void defaultSetCreatorSetIDBoxSelection()
        {
            if (setCreatorSetIDBox.Items.Count != 0)
            {
                setCreatorSetIDBox.SelectedIndex = 0;
            }
            else
            {
                unableToAddQuestion = true;
            }
        }

        /** Method: GetAllPublicQuestions
         * Grabs all available questions from Quizzer_Data_Access
         * 
        */

        private void GetAllPublicQuestions()
        {
            string allQuestions = dataAccess.GetAllQuestion();
            string[] questionArray = allQuestions.Split('\r');
            string[] splitQuestionInfo;
            string questionInfoShown;
            for (int questionCounter = 0; questionCounter < questionArray.Length - 1; questionCounter++)
            {
                splitQuestionInfo = questionArray[questionCounter].Split('|');
                if (splitQuestionInfo[QUIZZERDB_QUESTION_PUBLIC_INDEX] == "Yes")
                {
                    questionInfoShown = splitQuestionInfo[QUIZZERDB_QUESTION_QUESTIONID_INDEX] + " - " + splitQuestionInfo[QUIZZERDB_QUESTION_TITLE_INDEX];
                    questionComboBox.Items.Add(questionInfoShown);
                }
            }
        }

        /** Method: GetAllPublicQuestions
         * Overload
         * Grabs all available questions from Quizzer_Data_Access based on the professorID
         * @param professorID the professor's user id that the user is trying to get a question from
        */

        private void GetAllPublicQuestions(int professorID)
        {
            string allQuestions = dataAccess.GetAllQuestion();
            string[] questionArray = allQuestions.Split('\r');
            string[] splitQuestionInfo;
            string questionInfoShown;
            questionProfessorComboBox.Items.Clear();
            for (int questionCounter = 0; questionCounter < questionArray.Length - 1; questionCounter++)
            {
                splitQuestionInfo = questionArray[questionCounter].Split('|');
                if (splitQuestionInfo[QUIZZERDB_QUESTION_PUBLIC_INDEX] == "Yes" &&
                    Convert.ToInt32(splitQuestionInfo[QUIZZERDB_QUESTION_PROFESSORID_INDEX]) == professorID)
                {
                    questionInfoShown = splitQuestionInfo[QUIZZERDB_QUESTION_QUESTIONID_INDEX] + " - " + splitQuestionInfo[QUIZZERDB_QUESTION_TITLE_INDEX];
                    questionProfessorComboBox.Items.Add(questionInfoShown);
                }
            }
            defaultProfessorQuestionComboBoxSelection();
        }

        /**Method: populateQuestionRemoverComboBox
         * @author Jayson Park
         * Populates the question combo box with all of the questions in the selected game set.
         */

        private void populateQuestionRemoverComboBox()
        {
            if (dataAccess.GetAllGameSet().Trim() != "")
            {
                int currentGameSetIDRemove = Convert.ToInt32(((string)dataAccess.GetGameSet(((string)setCreatorRemoveSetIDBox.SelectedItem).Trim()).
                       Split('|').GetValue(QUIZZERDB_GAMESET_SETID_INDEX)).Trim());
                string[] questionsToRemoveForCurrentGameSet = dataAccess.questionsFromGameset(currentGameSetIDRemove).Split('\r');
                string[] questionRemoveHolder;
                questionRemoverComboBox.Items.Clear();
                for (int questionRemoveCounter = 0; questionRemoveCounter < questionsToRemoveForCurrentGameSet.Length - 1; questionRemoveCounter++)
                {
                    questionRemoveHolder = dataAccess.GetQuestion(Convert.ToInt32(questionsToRemoveForCurrentGameSet[questionRemoveCounter])).Split('|');
                    questionRemoverComboBox.Items.Add(questionRemoveHolder[QUIZZERDB_QUESTION_QUESTIONID_INDEX] + " - " + questionRemoveHolder[QUIZZERDB_QUESTION_TITLE_INDEX]);
                }
                defaultQuestionRemoverComboBoxSelection();
            }
        }

        /**Method: populateQuestionRemoverComboBox
         * @author Jayson Park
         * Populates the question combo box with all of the questions in the selected game set.
         */

        private void populateProfessorComboBox()
        {
            //Gets all the professors and puts them in an array

            String[] getAllProfessors = dataAccess.GetAllProfessor().Split('\n');

            //Puts all the professors into a combo box
            String[] getProfessor;
            string professorEmail;

            for (int counter = 0; counter < getAllProfessors.Length - 1; counter++)
            {
                getProfessor = ((String)(getAllProfessors.GetValue(counter))).Split('|');
                professorEmail = (String)getProfessor.GetValue(QUIZZERDB_PROFESSOR_EMAIL_INDEX);
                if (!(Convert.ToInt32(getProfessor.GetValue(QUIZZERDB_PROFESSOR_USERID_INDEX)) == ADMIN_LOGIN_USERID) &&
                    !(Convert.ToInt32(getProfessor.GetValue(QUIZZERDB_PROFESSOR_USERID_INDEX)) == userid))
                {
                    lookupProfessorComboBox.Items.Add(professorEmail);
                }
            }
            defaultProfessorEmailSelection();
        }

        /** Method: GetAllPublicSets
         * Grabs all sets from the database and populates the set ID comboboxes.
        */

        private void GetAllPublicSets()
        {
            setCreatorSetIDBox.Items.Clear();
            setCreatorRemoveSetIDBox.Items.Clear();
            removeSetComboBox.Items.Clear();
            string allSets = dataAccess.GetAllGameSet();
            if (allSets != "")
            {
                string[] setArray = allSets.Trim().Split('\r');
                for (int setCounter = 0; setCounter < setArray.Length; setCounter++)
                {
                    setCreatorSetIDBox.Items.Add(((String)(setArray[setCounter])).Split('|').GetValue(QUIZZERDB_GAMESET_SETNAME_INDEX));
                    setCreatorRemoveSetIDBox.Items.Add(((String)(setArray[setCounter])).Split('|').GetValue(QUIZZERDB_GAMESET_SETNAME_INDEX));
                    removeSetComboBox.Items.Add(((String)(setArray[setCounter])).Split('|').GetValue(QUIZZERDB_GAMESET_SETNAME_INDEX));
                }
                setCreatorSetIDBox.SelectedIndex = 0;
                setCreatorRemoveSetIDBox.SelectedIndex = 0;
                removeSetComboBox.SelectedIndex = 0;
            }
        }

        /** Method: AddNewSet
         * @author Jayson Park
         * Adds a new gameset to the database
         * 
         * @param newSet the name of the new set
        */

        private void AddNewSet(String newSet)
        {
            if (dataAccess.GetGameSet(setIDBox.Text).Trim() != "")
            {
                MessageBox.Show("Duplicate GameSet Name Found!", "Set Creator Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            else
            {
                dataAccess.NewGameSet(setIDBox.Text);
                GetAllPublicSets();
                unableToAddQuestion = false;
                populateQuestionRemoverComboBox();
                MessageBox.Show(String.Concat("You have successfully added game set ",
                    ((string)setIDBox.Text).Trim(), "!"), "Successful Add!");
            }
        }

        /** Method: addNewSetIDButton_Click
         * @author Jayson Park
         * The event handler for adding a new set
         * 
         * @param sender sender of the action
         * @param e event is triggered
        */

        private void addNewSetIDButton_Click(object sender, EventArgs e)
        {
            if (setIDBox.Text == "")
            {
                MessageBox.Show("Set ID cannot be blank!", "Set Creator Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            else
            {
                AddNewSet(setIDBox.Text);
                setIDBox.Text = "";
            }
        }

        /** Method: AddQuestionToSet
         * @author Samuel McCravy, Jayson Park
         * The event handler for adding a new set
         * 
         * @param questionID the question ID number of the question to add
        */

        private void AddQuestionToSet(int questionID)
        {
            int setID = Convert.ToInt32(((string)dataAccess.GetGameSet(((string)setCreatorSetIDBox.SelectedItem).Trim()).
               Split('|').GetValue(QUIZZERDB_GAMESET_SETID_INDEX)).Trim());
            try
            {
                Boolean duplicateDetected = checkDuplicateAdd(questionID, setID);

                if (duplicateDetected == false)
                {
                    dataAccess.questionToGameset(questionID, setID);
                    MessageBox.Show(String.Concat("You have successfully added question ", questionID.ToString(),
                        " to the gameset ", ((string)setCreatorSetIDBox.SelectedItem).Trim(), "!"), "Successful Add!");
                }
                else
                {
                    MessageBox.Show("Question is already in the Game set", "Error!");
                }
                populateQuestionRemoverComboBox();
            }
            catch (Exception caught)
            {
                MessageBox.Show("There was an error when writing to the database", "Error!");
                System.Diagnostics.EventLog.WriteEntry("Database write fail.", caught.StackTrace,
                   System.Diagnostics.EventLogEntryType.Warning);
            }
        }

        /** Method: checkDuplicateAdd
         * @author Jayson Park
         * Checks if the question was already added into the game set.
         * 
         * @param questionID the question ID number of the question to add
         * @param setID the ID number of the set to add the question to
         * @return a boolean flag dependent on whether a duplicate question was found
        */

        private Boolean checkDuplicateAdd(int questionID, int setID)
        {
            string[] questionsGameSet = (((string)dataAccess.questionsFromGameset(setID)).Trim()).Split('\r');
            for (int questionGameSetCounter = 0; questionGameSetCounter < questionsGameSet.Length; questionGameSetCounter++)
            {
                if (questionsGameSet[questionGameSetCounter].Trim() != "")
                {
                    if (int.Parse(questionsGameSet[questionGameSetCounter]) == questionID)
                    {
                        return (true);
                    }
                }
            }
            return (false);
        }

        /** Method: addQuestionToIDButton_Click
         * @author Jayson Park
         * The event handler for adding a new question to an existing set
         * 
         * @param sender sender of the action
         * @param e event is triggered
        */

        private void addQuestionToIDButton_Click(object sender, EventArgs e)
        {
            if (unableToAddQuestion)
            {
                MessageBox.Show("Missing question or set!", "Set Creator Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            else
            {
                int questionID = Convert.ToInt32(((string)questionComboBox.Text.Split(' ').GetValue(SETCREATOR_QUESTIONID_INDEX)).Trim());
                AddQuestionToSet(questionID);
            }
        }

        /** Method: setCreatorRemoveSetIDBox_SelectedIndexChanged
         * @author Jayson Park
         * The event handler when the setID for removing questions from sets has a changed selected index
         * 
         * @param sender sender of the action
         * @param e event is triggered
        */

        private void setCreatorRemoveSetIDBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            populateQuestionRemoverComboBox();
        }

        /** Method: removeQuestionFromIDButton_Click
         * @author Jayson Park
         * The event handler for adding removing a question to an existing set
         * 
         * @param sender sender of the action
         * @param e event is triggered
        */

        private void removeQuestionFromIDButton_Click(object sender, EventArgs e)
        {
            if (questionRemoverComboBox.Text.Trim() != "")
            {
                int questionID = Convert.ToInt32(((string)questionRemoverComboBox.Text.Split(' ').GetValue(SETCREATOR_QUESTIONID_INDEX)).Trim());
                int gameSetID = Convert.ToInt32(((string)dataAccess.GetGameSet(((string)setCreatorRemoveSetIDBox.SelectedItem).Trim()).
                   Split('|').GetValue(QUIZZERDB_GAMESET_SETID_INDEX)).Trim());
                dataAccess.removeFromGameset(questionID, gameSetID);
                populateQuestionRemoverComboBox();
                MessageBox.Show(String.Concat("You have successfully removed question ", questionID.ToString(),
                    " from the gameset ", ((string)setCreatorRemoveSetIDBox.SelectedItem).Trim(), "!"), "Success Removal!");
            }
            else
            {
                MessageBox.Show("No question to remove!", "Set Question Removal Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
        }

        /** Method: addProfessorQuestionToSetIDButton_Click
         * @author Jayson Park
         * The event handler for adding a new question from another professor to an existing set
         * 
         * @param sender sender of the action
         * @param e event is triggered
        */

        private void addProfessorQuestionToSetIDButton_Click(object sender, EventArgs e)
        {
            if (missingProfessor || missingProfessorQuestion)
            {
                MessageBox.Show("Missing Professor Email or Professor Question!", "Set Creator Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            else
            {
                int questionID = Convert.ToInt32(((string)questionProfessorComboBox.Text.Split(' ').GetValue(SETCREATOR_QUESTIONID_INDEX)).Trim());
                AddQuestionToSet(questionID);
            }
        }

        /** Method: lookupProfessorComboBox_SelectedIndexChanged
         * @author Jayson Park
         * The event handler for when the lookupProfessorComboBox index changes
         * 
         * @param sender sender of the action
         * @param e event is triggered
        */

        private void lookupProfessorComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Gets all the professors and puts them in an array

            String[] getAllProfessors = dataAccess.GetAllProfessor().Split('\n');

            //Puts all the professors into a combo box
            String[] getProfessor;
            string professorEmail;

            int professorID;
            for (int counter = 0; counter < getAllProfessors.Length - 1; counter++)
            {
                getProfessor = ((String)(getAllProfessors.GetValue(counter))).Split('|');
                professorEmail = (String)getProfessor.GetValue(QUIZZERDB_PROFESSOR_EMAIL_INDEX);
                if (professorEmail.Trim().Equals(lookupProfessorComboBox.SelectedItem))
                {
                    professorID = Convert.ToInt32(getProfessor.GetValue(QUIZZERDB_PROFESSOR_USERID_INDEX));
                    GetAllPublicQuestions(professorID);
                }
            }
        }

        /** Method: removeSetFromDatabase
         * @author Spencer Estes and Jayson Park
         * The method called when removing sets from the database as weill as their associated question_gameset table
         * 
        */
        private void removeSetFromDatabase()
        {
            string s_setID = (string)removeSetComboBox.SelectedItem;
            string s_setInformation = dataAccess.GetGameSet(s_setID);

            //Parses the string set ID and returns the ID in integer form
            int i_setID = Convert.ToInt32(((string)s_setInformation.Split('|').GetValue(QUIZZERDB_GAMESET_SETID_INDEX)).Trim());
            Console.WriteLine(i_setID);
            //Remove the associated Question_Gameset table
            deleteGameSetsFromQuestion_Gamesets(i_setID);

            //Delete the Gameset table
            dataAccess.DeleteGameSetRecord(i_setID);

            //User feedback
            string messageBoxString = "" + s_setID + " has been successfully removed";
            MessageBox.Show(messageBoxString, "Set Removal", MessageBoxButtons.OK);
        }

        /** Method: deleteGameSetsFromQuestion_GameSets
         * @author Spencer Estes and Jayson Park
         * The method called to remove a question_gameset table when deleting gamesets
         * 
         * @param gamesetID The ID of the gameset
        */
        private void deleteGameSetsFromQuestion_Gamesets(int gamesetID)
        {
            //Gets all the questions associated with the gameset
            String[] getAllQuestionsWithGameSet = (dataAccess.questionsFromGameset(gamesetID).Trim()).Split('\n');
            int questionID;

            //Removes all the questions so that Gameset deletion can take place
            for (int questionCounter = 0; questionCounter < getAllQuestionsWithGameSet.Length; questionCounter++)
            {
                if (((String)getAllQuestionsWithGameSet.GetValue(questionCounter)).Trim() != "")
                {
                    questionID = int.Parse(((String)getAllQuestionsWithGameSet.GetValue(questionCounter)).Trim());
                    dataAccess.removeFromGameset(questionID, gamesetID);
                }
            }
        }

        /** Method: removeSetButton_Click
         * @author Spencer Estes and Jayson Park
         * The event handler for when the "Remove Set" button has been clicked. Activates the method necessary to 
         * remove a gameset from the database
         * 
         * @param sender sender of the action
         * @param e event is triggered
        */
        private void removeSetButton_Click(object sender, EventArgs e)
        {
            DialogResult dialogResult = MessageBox.Show("Are you sure you wish to remove this game set?", "Confirmation", MessageBoxButtons.YesNo);
            if (dialogResult == DialogResult.Yes)
            {
                removeSetFromDatabase();
                GetAllPublicSets();
            }
        }
    }
}